package routes

import (
	"fmt"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/bean/oauthBean"
	"gitee.com/gitee-go/core/common"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/server/service"
	"gitee.com/gitee-go/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strings"
	"time"
)

type SourceInfo struct {
	Name            string `json:"name"`
	Title           string `json:"title"`
	Self            bool   `json:"self"`
	Host            string `json:"host"`
	Callback        string `json:"callback"`
	OauthCreatePath string `json:"oauthCreatePath"`
}
type SourceConf struct {
	Source       string `json:"source"`
	SourceHost   string `json:"sourceHost"`
	ClientId     string `json:"clientId"`
	ClientSecret string `json:"clientSecret"`
}

func (InstallController) check(c *gin.Context) {
	core.NewUIResOk("ok").ResJson(c)
}
func (cs *InstallController) hosts(c *gin.Context, m *struct {
	Host string `json:"host"`
}) {
	if strings.HasSuffix(m.Host, "/") {
		n := len(m.Host)
		m.Host = m.Host[:n-1]
	}
	if m.Host == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}

	req, err := http.NewRequest("GET", m.Host+"/api/install/check", nil)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("无法访问此host,请使用外网地址").
			ResJson(c)
		return
	}
	cli := &http.Client{}
	cli.Timeout = time.Second * 5
	res, err := cli.Do(req)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("无法通过host访问服务").
			ResJson(c)
		return
	}

	ls := []*SourceInfo{
		{Name: common.SourceGitee, Title: "Gitee", Self: false, Host: "https://gitee.com", OauthCreatePath: "/oauth/applications"},
	}
	for _, v := range ls {
		v.Callback = m.Host + "/api/login/oauth/back/" + v.Name
	}
	rt := utils.Map{
		"loginUrl": m.Host + "/login",
		"sources":  ls,
	}
	cs.host = m.Host
	core.NewUIResOk(rt).ResJson(c)
}

// 把前端配置的数据写入配置文件:application.yaml
// 1. 检查数据
// 2. 判断平台
// 3. 获取默认数据(环境变量)
// 4. 写入yaml
func (cs *InstallController) source(c *gin.Context, m *SourceConf) {
	/*if m.Host == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}*/
	if cs.host == "" || m.Source == "" || m.ClientId == "" || m.ClientSecret == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	if m.SourceHost != "" {
		if strings.HasSuffix(m.SourceHost, "/") {
			n := len(m.SourceHost)
			m.SourceHost = m.SourceHost[:n-1]
		}
	}

	switch m.Source {
	case common.SourceGitee:
		if m.SourceHost == "" {
			m.SourceHost = "https://gitee.com"
		}
	default:
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("未找到数据源").
			ResJson(c)
		return
	}
	par := &oauthBean.ParamOAuth{Source: make(map[string]*oauthBean.AppInfo)}
	par.Source[m.Source] = &oauthBean.AppInfo{
		ClientId:     m.ClientId,
		ClientSecret: m.ClientSecret,
		SourceHost:   m.SourceHost,
	}
	err := service.SetsParam(oauthBean.ParamOAuthKey, par)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}

	cs.ymlConf.ServerConf = &comm.Server{
		Host:     cs.host,
		Port:     fmt.Sprintf("%d", comm.Port),
		LoginKey: utils.RandomString(28),
		LimitConf: &comm.Limit{
			BuildLimit: 50,
			ParseLimit: 50,
		},
		WorkPath: utils.EnvDefault("GITEEGO_WORKSPACE"),
	}
	hs, errhs := os.Hostname()
	if cs.ymlConf.ServerConf.WorkPath == "" && errhs == nil && hs == "server" {
		cs.ymlConf.ServerConf.WorkPath = "/data"
	}
	cs.ymlConf.RunnerConf = &comm.Runner{
		Port:       utils.EnvDefault("RUNNER_PORT", "7030"),
		Secret:     utils.EnvDefault("RUNNER_SECRET", utils.RandomString(32)),
		MainRunner: true,
	}
	err = cs.saveConf()
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk().ResJson(c)
}
